package SGEngine

import (
	//"fmt"
	"freetypego"
	"strconv"
)

var IsFreetypeInit bool

func init() {
	IsFreetypeInit = false
}

type FreetypeChar struct {
	Mfont      *FreetypeFont
	Size       int
	CharCode   int
	AtlasIndex uint8
	Rect       PackRect
	BBox       freetypego.FT_BBox
	AdvanceX   int
}

type FreetypeFont struct {
	MaxAtlasSize int
	CurMaxAtlas  uint8
	faceIndex    freetypego.FT_Face
	CurSize      int
	TextureAtlas []*FreetypeAtlas
	CharMap      map[string]*FreetypeChar
}

func NewFont(path string) *FreetypeFont {
	RFont := new(FreetypeFont)
	RFont.CharMap = make(map[string]*FreetypeChar)
	if IsFreetypeInit == false {
		freetypego.InitFreeType()
		IsFreetypeInit = true
	}
	RFont.faceIndex = freetypego.FT_New_Face(path)
	RFont.CurMaxAtlas = 0
	RFont.MaxAtlasSize = 512
	FTAtlas := newFreetypeAtlas(RFont.MaxAtlasSize, RFont.MaxAtlasSize)
	RFont.TextureAtlas = append(RFont.TextureAtlas, FTAtlas)
	return RFont
}

func (f *FreetypeFont) GetChar(_char rune, Size int) *FreetypeChar {
	key := string(_char) + strconv.Itoa(Size)
	v, isHave := f.CharMap[key]
	if isHave {
		return v
	}
	return f.FillChatToFont(_char, Size)
}

func (f *FreetypeFont) FillChatToFont(_char rune, Size int) *FreetypeChar {
	if f.CurSize != Size {
		freetypego.Face_Set_Pixel_Sizes(int(f.faceIndex), Size, Size)
		f.CurSize = Size
	}
	fontChar := new(FreetypeChar)
	fontChar.AtlasIndex = f.CurMaxAtlas
	fontChar.CharCode = int(_char)
	fontChar.Size = Size
	fontChar.Mfont = f
	key := string(_char) + strconv.Itoa(Size)
	f.CharMap[key] = fontChar
	f.TextureAtlas[fontChar.AtlasIndex].AddCharToAtlas(fontChar)

	return fontChar
}
